package com.xie.test;

import org.joda.time.DateTime;

import java.math.BigDecimal;

/**
 * @author xiezhendong
 * @date 2021/11/2
 */
public class test6 {

    public static final int THREE_DECIMAL_PLACES = 3;

    public static void main(String[] args) throws Exception {
        DateTime startDate = new DateTime(1901, 2, 28, 3, 0, 0, 0);
        DateTime endDate = new DateTime(2021, 3, 3, 5, 0, 0, 0);

        long duration = test6.calculateDuration(startDate, endDate);
        if (duration < 0) {
            throw new Exception("TRAVEL_APPLICATION_DATE_ERROR_20015");
        }
        long start = System.currentTimeMillis();
        long durationDays = test6.calculateDurationDays1(startDate, endDate);
        long end = System.currentTimeMillis();
        System.out.println("calculateDurationDays1:" + (end - start));
        start = System.currentTimeMillis();
        long durationDays2 = test6.calculateDurationDays2(startDate, endDate);
        end = System.currentTimeMillis();
        System.out.println("calculateDurationDays2:" + (end - start));
        Double travelHours = test6.getDecimalValue(THREE_DECIMAL_PLACES, BigDecimal.valueOf(duration).divide(BigDecimal.valueOf(1000 * 60), 2)).doubleValue();
        Double travelDays = test6.getDecimalValue(THREE_DECIMAL_PLACES, BigDecimal.valueOf(durationDays)).doubleValue();
        Double travelDays2 = test6.getDecimalValue(THREE_DECIMAL_PLACES, BigDecimal.valueOf(durationDays2)).doubleValue();

        System.out.println("travelHours:" + travelHours);
        System.out.println("travelDays:" + travelDays);
        System.out.println("travelDays2:" + travelDays2);
    }

    private static long calculateDurationDays2(DateTime startDate, DateTime endDate) {
        long days = 1L;
        startDate = startDate.withTimeAtStartOfDay();
        endDate = endDate.withTimeAtStartOfDay();
        while (startDate.getMillis() != endDate.getMillis()) {
            startDate = new DateTime(startDate.getMillis() + (1000 * 60 * 60 * 24));
            days++;
        }
        return days;
    }

    private static long calculateDurationDays1(DateTime startDate, DateTime endDate) {
        //出差时长/出差天数
        long start = startDate.withTimeAtStartOfDay().getMillis();
        long end = endDate.withTimeAtStartOfDay().getMillis();
        long days = (end - start) / (1000 * 60 * 60 * 24);
        return days + 1;
    }

    /**
     * 计算天数
     *
     * @param startDate
     * @param endDate
     * @return
     */
    static long calculateDuration(DateTime startDate, DateTime endDate) {
        //出差时长/出差天数
        long duration = endDate.getMillis() - startDate.getMillis();
        return duration;
    }

    public static BigDecimal getDecimalValue(int place, BigDecimal bigDecimal) {
        return bigDecimal.setScale(place, BigDecimal.ROUND_HALF_UP);
    }
}
